package com.zls.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class SpringSecurityController {
    @RequestMapping("test")
    public String test(){
        return "test";
    }

    @RequestMapping("/show/name")
    public String showName(){
        //认证对象
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof User){
            User user= (User) principal;
            return user.getUsername();
        }
        //未认证过，但是经过Security框架，那么会有一个临时用户 anonymousUser
        return principal.toString();
    }
}
